﻿Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Reflection

''' <summary>
''' Nombre			: Utils
''' Descripción		: Métodos generales para la capa de acceso a datos
''' </summary>
''' <remarks>
''' Creacion        : 11/07/2014 Daniel La Torre L.
''' Modificacion    : 
''' </remarks>
Public Class Utils
    ''' <summary>
    ''' Crea un objeto tipificado a partir de un objeto SQLDataReader
    ''' </summary>
    ''' <param name="obj">Objeto a llenar</param>
    ''' <param name="dr">SQLDataReader con el que se llenar� el objeto</param>
    ''' <returns>Retorna un objeto tipificado</returns>
    Public Shared Function CreaObjeto(Of T)(ByRef obj As T, ByVal dr As SqlDataReader) As T
        Dim type As Type = GetType(T)
        Dim indice As Integer = 0
        For Each pi As PropertyInfo In type.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
            If (indice >= dr.FieldCount) Then
                Exit For
            End If
            If Not dr.GetValue(indice).Equals(DBNull.Value) Then

                obj.[GetType]().GetProperty(pi.Name).SetValue(obj, dr.GetValue(indice), Nothing)
               

            End If
            indice += 1
        Next
        Return obj
    End Function

    ''' <summary>
    ''' Crea una lista gen�rica de objetos tipificados a partir de un objeto SQLDataReader
    ''' </summary>
    ''' <param name="lstObj">Lista gen�rica a llenar</param>
    ''' <param name="dr">SQLDataReader con el que se llenar� la lista gen�rica</param>
    ''' <returns>Retorna una lista gen�rica</returns>
    Public Shared Function CreaLista(Of T)(ByRef lstObj As List(Of T), ByVal dr As SqlDataReader, Optional ByVal ignorarPrimerCursor As Boolean = False) As List(Of T)
        If dr.HasRows Then
            If ignorarPrimerCursor Then
                If dr.Read() Then
                    dr.NextResult()
                End If
            End If
            While dr.Read()
                Dim type As Type = GetType(T)
                Dim obj As T = DirectCast(Activator.CreateInstance(type), T)
                lstObj.Add(CreaObjeto(obj, dr))
            End While
        End If
        Return lstObj
    End Function
End Class